package com.abhinav;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class JoinTest {
	public static void main(String[] args) {
		Thread t1, t2, t3;
		 t1 = new Thread(new Joiner1()); t1.start();
		 t2 = new Thread(new Joiner2()); t2.start();
		 t3 = new Thread(new Joiner3()); t3.start();
		
		ExecutorService exec = Executors.newCachedThreadPool();
//		exec.execute(new Joiner1());
//		exec.execute(new Joiner2());
//		exec.execute(new Joiner3());
		
		exec.execute(new CallJoiner(t1, t2, t3));
		
		exec.shutdown();
		 
//		 Thread t4 = new Thread(new CallJoiner(t1, t2, t3));
//		 t4.start();
		
	}
	
}

class CallJoiner extends Thread {
	private Thread j1, j2, j3;
	
	 public CallJoiner(Thread j1, Thread j2, Thread j3){
		 this.j1 = j1;
		 this.j2 = j2;
		 this.j3 = j3;
	 }

	@Override
	public void run() {
		try {
			j1.join();
			j2.join();
			j3.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + "Completed..");
	}
	
}

class Joiner1 implements Runnable{

	@Override
	public void run() {
		try {
			System.out.println(Thread.currentThread().getName() +"going to sleep for 1 sec..");
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() +"completed..");
	}
	
}

class Joiner2 implements Runnable{

	@Override
	public void run() {
		try {
			System.out.println(Thread.currentThread().getName() +"going to sleep for 2 sec..");
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() +"completed..");
	}
	
}

class Joiner3 implements Runnable{

	@Override
	public void run() {
		try {
			System.out.println(Thread.currentThread().getName() +"going to sleep for 3 sec..");
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() +"completed..");
	}
	
}